package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private ClazzService clazzService;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<Student> findList(StudentQueryParam student) {

        // 获取 page 对象
        Page<Student> studentPage = new Page<>(student.getPage(), student.getPageSize());
        // 根据更新时间排序
        studentPage.addOrder(OrderItem.desc("update_time"));

        // 创建查询条件
        LambdaQueryWrapper<Student> queryWrapper = Wrappers.<Student>lambdaQuery().like(student.getName() != null, Student::getName, student.getName())
                .eq(student.getDegree() != null, Student::getDegree, student.getDegree())
                .eq(student.getClazzId() != null, Student::getClazzId, student.getClazzId());

        // 封装数据
        Page<Student> page = page(studentPage, queryWrapper);
        List<Student> studentList = page.getRecords();

        // 获取所有班级
        List<Clazz> clazzList = clazzService.list();

        // 把 班级主键 和 班级name 提取到Map里
        Map<Integer, String> clazzMap = clazzList.stream().collect(Collectors.toMap(Clazz::getId, Clazz::getName));

        // 将Student的班级名称属性 补充
        studentList.forEach(student1 -> {
            if(student1.getClazzId() != null){
                student1.setClazzName(clazzMap.get(student1.getClazzId()));
            }
        });

        return new PageResult<>(page.getTotal(), studentList);
    }

    /**
     * 学生违规   违规次数 + 1   违规分数 = 违规分数 + score
     *
     * @param id    学生 Id
     * @param score 违规分数
     */
    @Override
    public void updateStudentVio(Integer id, Integer score) {
        // 构建更新条件
        studentMapper.updateStudentVio(id, score);
    }
}
